import { ajax ,getBusinessInfo ,toast} from "nc-lightapp-front";
import {ArapConstant,parentItemKey,childrenItemKey,IBillFieldGet,FromSystem,ArapBillVOConsts,
    billstatus,effectstatus,approvestatus,INDEX_PK,headkey,bodykey,crBodykey,deBodykey}from './arapCopyConstant' ;


/**
 * 收付单据列表操作列复制功能
 * @param {*} that 
 */
let listCopyBill = (that) => {
    ajax({
        url: '/nccloud/arap/arappub/copy.do',
        data: {
            pk_bill: that.props.getUrlParam('id'),
            pageId: that.getPagecode(),
            billType: that.billType,
            type: 1,
            tradeType: that.getPagecode()
        },
        success: (res) => {
            that.props.beforeUpdatePage(); //打开开关
            if (res.data) {
                if (res.data.head) {
                    that.props.form.setAllFormValue({ [that.formId]: res.data.head[that.formId] });
                }
                if (res.data.body) {
                    that.props.cardTable.setTableData(that.tableId, res.data.body[that.tableId]);
                }
            }
            that.state.buttonfalg = true;
            that.props.cardTable.setStatus(that.tableId, 'edit');
            that.props.form.setFormStatus(that.formId, 'edit');
            that.props.updatePage(that.formId, that.tableId); //关闭开关
            that.toggleShow();
        },
        error: (res) => {
            that.props.form.EmptyAllFormValue(that.formId);
            that.props.cardTable.setTableData(that.tableId, { rows: [] });
            that.props.setUrlParam({ status: 'browse' });
            that.props.cardTable.setStatus(that.tableId, 'browse');
            that.props.form.setFormStatus(that.formId, 'browse');
            that.toggleShow();
            let str = res.message;
            toast({ color: 'danger', content: str});;
        }
    });
}  

/**
 * 复制单据公共的方法
 * @param {*} that 
 * @param {*} pageCode 
 */
let copyBill = (that,pageCode) =>{
    let cardData = that.props.createMasterChildData(pageCode, that.formId, that.tableId);
    let head = cardData.head[that.formId].rows[0];
    let bodys =  cardData.body[that.tableId].rows;
    let BillClass = head.values.billclass.value;
    let isrefund = head.values.isrefund.value;
    if(validateVoCopyRed(that,bodys,BillClass,isrefund)){
        return;
    }
    let businessInfo  = getBusinessInfo();
    let isInit = head.values.isinit.value;
    let returndate=null;
    //期初单据获取单据日期  以及复制单据的时候获取单据流程
    let busitypeMap = '';
    ajax({
        url: '/nccloud/arap/arappub/getBusitypeAndBilldate.do',
        async :false,
        data:Object.assign({
            isInit: isInit,
            pk_org: head.values.pk_org.value ? head.values.pk_org.value:head.values.pk_org_v.value,
            pk_billtype: head.values.pk_billtype.value,
            pk_tradetype: head.values.pk_tradetype.value,
            creator:head.values.creator.value
        },that.dataInSaga),
        success: (res) => {
            busitypeMap = res.data;
            returndate=res;
        }
    });

    that.props.beforeUpdatePage(); //打开开关
    copyParentVO(that,head,isInit,businessInfo,BillClass,busitypeMap);//复制表头
    copyChildrenVO(that,bodys,isInit,businessInfo,BillClass,busitypeMap);//复制表体
    processImpMoney(head,bodys,BillClass);//重新计算金额
    that.props.form.setAllFormValue({ [that.formId]: cardData.head[that.formId] });
    that.props.cardTable.setTableData(that.tableId, cardData.body[that.tableId]);
    that.props.setUrlParam({ status: 'add', type: 'copy' });
    that.state.buttonfalg = true;
    that.props.resMetaAfterPkorgEdit();
    that.props.form.setFormItemsDisabled(that.formId, { pk_org: false ,pk_org_v: false});
    that.props.cardTable.setStatus(that.tableId, 'edit');
    that.props.form.setFormStatus(that.formId, 'edit');
    that.props.updatePage(that.formId, that.tableId); //关闭开关
    that.toggleShow('',returndate);
  
}

//重新计算金额，构造一个map到后台构造一个aggvo用于计算金额
let processImpMoney = (head,bodys,BillClass) =>{
    
    let  headMap = new Map();
    for(let i = 0 ; i <headkey.length ;i ++){
        headMap.set(headkey[i],head.values[headkey[i]].value);
    }
    let direction = bodys[0].values.direction.value;
    
    let bodysMap = new Map();
    //应收单和付款单 DebitEnvironment
    if(direction == 1 ){//借方
        let bodsykey =  bodykey.concat(deBodykey);
        for(let i = 0 ; i< bodys.length ; i++){
            let bodyMap = new Map();
            for(let j = 0 ; j<bodsykey.length ; j++){
                bodyMap.set(bodsykey[j],bodys[i].values[bodsykey[j]] ? bodys[i].values[bodsykey[j]].value :null);
            }
            bodysMap.set(i ,bodyMap);
        }
       
    }
    //应付单和收款单 CreditEnvironment
    if(direction == -1){//贷方     
        let bodsykey =  bodykey.concat(crBodykey);
        for(let i = 0 ; i< bodys.length ; i++){
            let bodyMap = new Map();
            for(let j = 0 ; j<bodsykey.length ; j++){
                bodyMap.set(bodsykey[j],bodys[i].values[bodsykey[j]]  ? bodys[i].values[bodsykey[j]].value :null);
            }
            bodysMap.set(i ,bodyMap);
        }
    }
    ajax({
        url: '/nccloud/arap/arappub/processImpMoney.do',
        async :false,
        data: {
            BillClass:BillClass,
            head: headMap,
            bodys : bodysMap
        },
        success: (res) => {
            //给计算的字段重新赋值
            let parent = res.data.parent;
            Object.keys(parent).map((key) => {
                if(parent[key]  && head.values[key] && !head.values[key].display){
                    let keyScale = head.values[key].scale;
                    if(keyScale && keyScale !=-1 ){
                        head.values[key].value = addZero(parent[key],keyScale);
                    }else{
                        head.values[key].value = parent[key];
                    }
                }
            })
            let childrens = res.data.children[0];
            for(let i = 0 ;i < childrens.length ; i ++){
                let children = childrens[i];
                let body = bodys[i];
                Object.keys(children).map((key) => {
                    if(children[key] && body.values[key] && !body.values[key].display){
                        let keyScale = body.values[key].scale;
                        if(keyScale && keyScale !=-1){
                            body.values[key].value = addZero(children[key],keyScale);
                        }else{
                            body.values[key].value = children[key];
                        }
                    }
                })
            }
        }
    });



}



//复制头部
let copyParentVO = (that,head,isInit,businessInfo,BillClass,busitypeMap) =>{
    let userId = businessInfo.userId;//用户ID
    let userName = businessInfo.userName;//用户名称
    let groupId  = businessInfo.groupId;//集团Id
    let groupName = businessInfo.groupName;//集团名称
    let busiDate = businessInfo.businessDate;//业务日期
    Object.keys(head.values).map((key) => {
        if(parentItemKey.indexOf(key) !=-1){
            //清空value和display
            head.values[key].value =null;
            head.values[key].display =null;
        }
    });
    if(BillClass == IBillFieldGet.YS || BillClass ==IBillFieldGet.SK || BillClass ==IBillFieldGet.ZF ){
        head.values.src_syscode.value = FromSystem.AR;
        head.values.src_syscode.display = that.state.json['public-000218']; /* 国际化处理： 应收系统*/
    }else{
        head.values.src_syscode.value = FromSystem.AP;
        head.values.src_syscode.display = that.state.json['public-000219'];/* 国际化处理：应付系统*/
    }
    //清空主键
    let primaryKey=getHeadPk(BillClass);
    head.values[primaryKey].value=null;
    //transientFlag标识没有
    //saveTotemporarily标识没有
    if(BillClass == IBillFieldGet.FK || BillClass ==IBillFieldGet.SK){//付款单和收款单需要清空该标志
        head.values.settletype.value=ArapBillVOConsts.m_intJSZXZF_NONE;//结算类型
        head.values.settletype.display=that.state.json['public-000220'];/* 国际化处理：无结算方式*/
        head.values.settleflag.value=ArapBillVOConsts.m_intDJZzzt_Default;//结算状态
        head.values.settleflag.display =that.state.json['public-000221'];/* 国际化处理：默认*/
    }
    head.values.saga_frozen.value = '0';  
    head.values.isreded.value = false;//红冲标志
    head.values.isrefund.value = 'N';//退款标志
    head.values.pk_group.value = groupId;//集团信息
    head.values.pk_group.display = groupName; 
    head.values.creator.value = userId;//用户信息
    head.values.creator.display = userName;
    head.values.creationtime.value = busiDate;
    head.values.billdate.value = busiDate;
    head.values.busidate.value = busiDate;//.split(' ')[0]
    head.values.billmaker.value = userId;
    head.values.billmaker.display = userName;
    if(isInit){//如果是期初
        let billdate = busitypeMap.billdate;//期初单据，该处需要ajax访问后台返回单据日期，先空着
        head.values.billdate.value = billdate;
        head.values.busidate.value = billdate;
        head.values.billstatus.value = billstatus.AUDIT;
        head.values.billstatus.display =that.state.json['public-000222'];/* 国际化处理：审批通过*/
		head.values.effectdate.value = billdate;
        head.values.effectstatus.value = effectstatus.EXECUTED;
        head.values.effectstatus.display = that.state.json['public-000223'];/* 国际化处理：已生效*/
        head.values.effectuser.value = userId;
        head.values.effectuser.display = userName;
        head.values.approvestatus.value = approvestatus.PASSING;
        head.values.approvestatus.display = that.state.json['public-000222'];/* 国际化处理：审批通过*/
        head.values.approver.value = userId;
        head.values.approver.display = userName;
        head.values.approvedate.value = billdate;
    }else{
        head.values.billstatus.display = that.state.json['public-000224'];/* 国际化处理：保存态*/
        head.values.billstatus.value = billstatus.SAVE;
        head.values.effectstatus.value = effectstatus.INVALID;
        head.values.effectstatus.display = that.state.json['public-000225'];/* 国际化处理：未生效*/
        //新加的
        head.values.approvestatus.value = approvestatus.NOSTATE;
        head.values.approvestatus.display = that.state.json['public-000226'];/* 国际化处理：自由*/
    }
    let pk_busitype =busitypeMap.pk_busitype;//业务流程需要访问后台
    let pk_busitypeName = busitypeMap.pk_busitypeName;//业务流程名称
    head.values.pk_busitype.value = pk_busitype;
    head.values.pk_busitype.display = pk_busitypeName;
}
//复制表体
let copyChildrenVO = (that,bodys,isInit,businessInfo,BillClass,busitypeMap) =>{
    let groupId  = businessInfo.groupId;//集团Id
    let groupName = businessInfo.groupName;//集团名称
    let busiDate = businessInfo.businessDate;//业务日期
    for(let i = 0 ; i < bodys.length ; i++){
        let body = bodys[i];
        body.status = '2';//修改状态为新增
        Object.keys(body.values).map((key) => {
            if(childrenItemKey.indexOf(key) !=-1){
                //清空value和display
                body.values[key].value =null;
                body.values[key].display =null;
            }
        });
        let primaryKey = getBodyPk(BillClass);
        body.values[primaryKey].value=INDEX_PK+body.values.rowno.value;//设置虚拟pk, 为结算分拆行做映射的key
         //清空主键
        let parentKey=getHeadPk(BillClass);
        body.values[parentKey].value=null;
        body.values.settlemoney.value = addZero(0,body.values.settlemoney.scale);
        body.values.settlecurr.value = null;
        body.values.settlecurr.display = null;
        body.values.rate.value = addZero(0,body.values.settlemoney.scale);
        body.values.grouprate.value = addZero(0,body.values.settlemoney.scale);
        body.values.globalrate.value = addZero(0,body.values.settlemoney.scale);
        if(isInit){//如果是期初
            let billdate = busitypeMap.billdate;//期初单据，该处需要ajax访问后台返回单据日期，先空着
            body.values.billdate.value = billdate;
            body.values.busidate.value = billdate;
        }else{
            body.values.billdate.value = busiDate;
            body.values.busidate.value = busiDate;
        }
        body.values.pk_group.value = groupId;//集团信息
        body.values.pk_group.display = groupName;
        if(BillClass == IBillFieldGet.YS || BillClass == IBillFieldGet.FK){
            body.values.money_bal.value = body.values.money_de.value;
            body.values.occupationmny.value = body.values.money_de.value;
            body.values.local_money_bal.value = body.values.local_money_de.value;
        }else if (BillClass == IBillFieldGet.YF || BillClass == IBillFieldGet.SK){
            body.values.money_bal.value = body.values.money_cr.value;
            body.values.occupationmny.value = body.values.money_cr.value;
            body.values.local_money_bal.value = body.values.local_money_cr.value;
        }

    }

}





/**
 * 检验单据是否可以复制
 */
let validateVoCopyRed = (that,bodys,BillClass,isrefund) =>{
   
    //判断往来对象为客户的付款单应不能复制，
    //往来对象为供应商的收款单应不能复制，这部分逻辑应尽量按照规则提取到收款单付款单各自的组件中.
    for(let i=0 ;i <bodys.length; i++){
        if(BillClass == ArapConstant.ARAP_FK_BILLCLASS){
            if(bodys[i].values.objtype.value == ArapConstant.ASSO_OBJ_CUSTOMER&&isrefund){
                toast({ color: 'danger', content: that.state.json['public-000240'] }); /* 国际化处理：退款付款单不能执行该操作！*/
                return true;
            }
        }
        if(BillClass == ArapConstant.ARAP_AP_BILLCLASS){
            if(bodys[i].values.objtype.value == ArapConstant.ASSO_OBJ_CUSTOMER&&isrefund){
                toast({ color: 'danger', content: that.state.json['public-000239'] }); /* 国际化处理：退款应付单不能执行该操作！*/
                return true;
            }
        }
        if(BillClass == ArapConstant.ARAP_SK_BILLCLASS){
            if(bodys[i].values.objtype.value == ArapConstant.ASSO_OBJ_SUPPLIER&&isrefund){
                toast({ color: 'danger', content: that.state.json['public-000241'] }); /* 国际化处理：退款收款单不能执行该操作！*/
                return true;
            }
        }
    }
    return false;
}

//根据单据大类获取头部pk主键
let getHeadPk = (BillClass) => {
    if(BillClass == IBillFieldGet.YS){//应收单
        return 'pk_recbill';
    }else if (BillClass == IBillFieldGet.YF){//应付单
        return 'pk_payablebill'; 
    }else if (BillClass == IBillFieldGet.FK){//付款单
        return 'pk_paybill'; 
    }else if (BillClass == IBillFieldGet.SK){//收款单
        return 'pk_gatherbill'; 
    }else if (BillClass == IBillFieldGet.ZF){//暂估应付单
        return 'pk_estipayablebill'; 
    }else if (BillClass == IBillFieldGet.ZS){//未确认应收单
        return 'pk_estirecbill'; 
    }
}

//根据单据大类获取子表主键
let getBodyPk = (BillClass) => {
    if(BillClass == IBillFieldGet.YS){//应收单
        return 'pk_recitem';
    }else if (BillClass == IBillFieldGet.YF){//应付单
        return 'pk_payableitem'; 
    }else if (BillClass == IBillFieldGet.FK){//付款单
        return 'pk_payitem'; 
    }else if (BillClass == IBillFieldGet.SK){//收款单
        return 'pk_gatheritem'; 
    }else if (BillClass == IBillFieldGet.ZF){//暂估应付单
        return 'pk_estipayableitem'; 
    }else if (BillClass == IBillFieldGet.ZS){//未确认应收单
        return 'pk_estirecitem'; 
    }
}

//金币的时候，根据精度设置值
let addZero = (num, scale) => {
    if (isNaN(Number(num)) || !num) {
        return null;
    }
    let _num = num.toString()
    if (scale > 0) {
        let start = _num.split('.')[0];
        let end = _num.split('.')[1];
        if (!end) {
            end = '';
        }
        let len = end.length;
        if (len < scale) {//长度不够加0
            end = end.padEnd(scale, '0');
        }else{//长度够减0
            end = end.substr(0,scale);
        }
        return start + '.' + end;
    } else {
        return _num;
    }
}



export { listCopyBill, copyBill };